<?php
            
use app\model\Theme; 


/**
 * Author: cbw
 * Desc: 优惠券
 * Time: 2022/11/6 16:28
 * Email: 17854288794@163.com
 */
class Index_Page extends PluginWebPage {

    public function main()
    {
        global $_G,$_P,$_S,$_C;
        $method = 'coupon_main';
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $theme = Theme::getThemeById($themeid);
        $theme_bengin_time = date('Y-m-d H:i:s',$theme['begintime']);
        $theme_end_time = date('Y-m-d H:i:s',$theme['endtime']);

        $page_index = max(1,intval($_P['page']));
        $page_size = 10;
        $page_start = ($page_index-1)*$page_size;

        $target = isset($_P['target'])?$_P['target']:0;
        $get_type = isset($_P['get_type'])?$_P['get_type']:0;
        $show_type = isset($_P['show_type'])?$_P['show_type']:0;
        $used_type = isset($_P['used_type'])?$_P['used_type']:0;
        $status = isset($_P['status'])?$_P['status']:0;

        $used_type_arr = $select_used_type_arr = CouponModel::couponArrByKey('used_type',$themeid);
        $status_arr = CouponModel::couponArrByKey('status',$themeid);
        $get_type_arr = $select_get_type_arr =  CouponModel::couponArrByKey('get_type',$themeid);
        $show_type_arr = $select_show_type_arr = CouponModel::couponArrByKey('show_type',$themeid);
        $select_show_type_arr = array_splice($select_show_type_arr,1);
        $select_used_type_arr = array_splice($select_used_type_arr,1);
        $select_get_type_arr = array_splice($select_get_type_arr,1);

        $is_presale = CouponModel::isPreSaleSoftMode($_S,$_C);

        if (empty($_P['createtime']['start'])){
            $starttime =  $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
            $start_day =  date('Y-m-d H:i:s',$start_day);
        }else{
            $starttime = $_P['createtime']['start'];
            $start_day = date("Y-m-d H:i:s",$_P['createtime']['start']);
        }
        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
        $end_day = empty($_P['createtime']['end']) ? date('Y-m-d H:i:s',time()): date("Y-m-d H:i:s",$_P['createtime']['end']) ;

        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }
        $check_coupon = CouponModel::couponListDataCheck($themeid);
        $total = CouponModel::couponListData($themeid,$target,$show_type,$used_type,$get_type,$status,0,$search_data,$page_start,0,$start_day,$end_day,true);
        $list = CouponModel::couponListData($themeid,$target,$show_type,$used_type,$get_type,$status,0,$search_data,$page_start,$page_size,$start_day,$end_day);
        foreach ($list as $k =>$v){
            $list[$k]['can_del'] = true;
            $used_total = CouponModel::couponUsedTotal($themeid,$v['id']);
            $get_total = CouponModel::couponUsedTotal($themeid,$v['id'],1);
            $list[$k]['get_total'] = $get_total;
            $list[$k]['use_total'] = $used_total;
            if ($used_total>0){
                $list[$k]['can_del'] = false;
            }
        }
//        dump($list);die();
        $pager = pagination($total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/coupon/index/main', $return_clicent);
    }

    public function add()
    {
        global $_G, $_P,$_S,$_C;
        $method = 'coupon_main';
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        if ($_G['ispost']){
            return $this->post();
        }else{
            $is_presale = CouponModel::isPreSaleSoftMode($_S,$_C);
            $target_arr = $select_target_arr  = CouponModel::couponArrByKey('target',$themeid);
            $get_type_arr = $select_get_type_arr =  CouponModel::couponArrByKey('get_type',$themeid);
            $show_type_arr = $select_show_type_arr = CouponModel::couponArrByKey('show_type',$themeid);
            $used_type_arr = $select_used_type_arr = CouponModel::couponArrByKey('used_type',$themeid);
            $status_arr = CouponModel::couponArrByKey('status',$themeid);
            $select_target_arr = array_splice($select_target_arr,1);
            $select_used_type_arr = array_splice($select_used_type_arr,1);
            $select_show_type_arr = array_splice($select_show_type_arr,1);
            $select_get_type_arr = array_splice($select_get_type_arr,1);
            $return_clicent = get_defined_vars();
return $this->view('/coupon/index/new', $return_clicent);
        }
    }

    public function edit()
    {
        global $_G, $_P,$_S,$_C;
        $method = 'coupon_main';
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        if($_G['ispost']){
            return $this->post();
        }else{
            $id = $_P['id'];
            $is_presale = CouponModel::isPreSaleSoftMode($_S,$_C);
            $items = db_get(t_yx_coupon,['themeid'=>$themeid,'id'=>$id]);
            $price_info = json_decode($items['price_info'],true);
            $max_id = 0;
            if ($price_info){
                foreach ($price_info as $k => $v){
                    if ($v['id']>$max_id){
                        $max_id = $v['id'];
                    }
                }
            }
            $max_id+=1;
            $target_arr = $select_target_arr  = CouponModel::couponArrByKey('target',$themeid);

            $get_type_arr = $select_get_type_arr =  CouponModel::couponArrByKey('get_type',$themeid);
            $show_type_arr = $select_show_type_arr = CouponModel::couponArrByKey('show_type',$themeid);
            $used_type_arr = $select_used_type_arr = CouponModel::couponArrByKey('used_type',$themeid);
            $status_arr = CouponModel::couponArrByKey('status',$themeid);
            $select_target_arr = array_splice($select_target_arr,1);
            $select_used_type_arr = array_splice($select_used_type_arr,1);
            $select_show_type_arr = array_splice($select_show_type_arr,1);
            $select_get_type_arr = array_splice($select_get_type_arr,1);
            //判断次优惠券是否有使用记录
            $used_total = CouponModel::couponUsedTotal($themeid,$id);
            $return_clicent = get_defined_vars();
return $this->view('/coupon/index/edit', $return_clicent);
        }

    }

    protected function post()
    {
        global $_G, $_P,$_S,$_C;;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        if (!$themeid){
            show_json(0,['msg'=>'活动入口不正确']);
            return;
        }
        if (!$_G['ispost']){
            show_json(0,['msg'=>'非法请求']);
            return;
        }else{
            $prize_info = [];
            $yx_lt_coupon_price_limit = $_P['yx_lt_coupon_price_limit'];
            $yx_coupon_rule_price_diff = $_P['yx_coupon_rule_price_diff'];
            $yx_coupon_price_id = $_P['yx_coupon_price_id'];
            if ($yx_coupon_rule_price_diff && $_C['coupon_use_type']==3){
                foreach ($yx_coupon_rule_price_diff as $k => $v)
                {
                    if ($v){
                        $tmp_arr = [
                            'id'=>$yx_coupon_price_id[$k],
                            'limit'=>$yx_lt_coupon_price_limit[$k],
                            'price'=>$v
                        ];
                        array_push($prize_info,$tmp_arr);
                    }

                }
            }
            if ($_C['coupon_use_type']!=3){
                $prize_info = [
                    ['id'=>1,'limit'=>0,'price'=>floatval($_P['price'])]
                ];
            }
            $name  = $_P['name']?$_P['name']:"";
            $price = $_P['price']?floatval($_P['price']):0;
            $max_price = $_P['max_price']?floatval($_P['max_price']):$price;
            $qty = $_P['qty']?$_P['qty']:0;
            $img = $_P['img']?tomedia($_P['img']):'';
            $target = $_P['target']?$_P['target']:1;
            $get_type = $_P['get_type']?$_P['get_type']:1;
            $show_type = $_P['show_type']?$_P['show_type']:1;
            $used_type = $_P['used_type']?$_P['used_type']:1;
            $get_start_time = $_P['gettime']['start'];
            $get_end_time = $_P['gettime']['end'];

            $used_start_time = $_P['usedtime']['start'];
            $used_end_time = $_P['usedtime']['end'];

            if (!$name){
                show_json(0,['msg'=>'优惠券名称不可为空']);
                return;
            }
            //判断大于100 整数
            //小于100 小数点后1位
            if ($price!=$max_price){
                if ($price>=100) {
                    if (!is_int($price)) {
                        $price = intval($price);
                    }
                }else{
                    $float_length = $this->getFloatLength($price);
                    if ($float_length>1){
                        $price = round($price, 1, PHP_ROUND_HALF_DOWN);
                    }
                }
                if ($max_price>=100){
                    if (!is_int($price)) {
                        $max_price = intval($price);
                    }
                }else{
                    $float_length = $this->getFloatLength($price);
                    if ($float_length>1){
                        $max_price= round($price, 1, PHP_ROUND_HALF_DOWN);
                    }
                }
            }else{
                if ($price>=100) {
                    if (!is_int($price)) {
                        $price = $max_price = intval($price);
                    }
                }else{
                    $float_length = $this->getFloatLength($price);
                    if ($float_length>1){
                        $price = $max_price= round($price, 1, PHP_ROUND_HALF_DOWN);
                    }
                }
            }



            $shangjiaid = $_P['shangjiaid']?$_P['shangjiaid']:0;
            $status = $_P['status'];
            if (!$price && $yx_coupon_rule_price_diff){
                $price = $yx_coupon_rule_price_diff [0];
            }

            $id = $_P['id']?$_P['id']:0;
            $data = [
                'shangjiaid'=>$shangjiaid,
                'name'=>$name,
                'price'=>$price,
                'price_info'=>json_encode($prize_info),
                'qty'=>$qty,
                'target'=>$target,
                'get_type'=>$get_type,
                'show_type'=>$show_type,
                'used_type'=>$used_type,
                'img'=>$img,
                'get_start_time'=>$get_start_time,
                'get_end_time'=>$get_end_time,
                'used_start_time'=>$used_start_time,
                'used_end_time'=>$used_end_time,
                'status'=>$status,
                'themeid'=>$themeid,
                'max_price'=>$max_price,
            ];
            if (!$id){
                $res = $insertid = db_insert(t_yx_coupon,$data);
            }else{
                $where = ['id'=>$id];
                $res = db_update(t_yx_coupon,$data,$where);
            }

            if (!$res){
                show_json(0,['msg'=>'操作失败']);
            }else{
                show_json(1,['msg'=>'操作成功']);
            }
        }
    }

    public function delItem()
    {
        global $_G,$_P,$_S,$_C;
        $method = 'coupon_main';
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $theme = Theme::getThemeById($themeid);
        $id = $_P['id'];
        $res = db_delete(t_yx_coupon,['themeid'=>$themeid,'id'=>$id]);
        if (!$res){
            show_json(0,['msg'=>'操作失败']);
        }else{
            show_json(1,['msg'=>'操作成功']);
        }
    }

    /**
     * Desc:用户补发优惠券
     * Author:cbw
     * Time: 2023/8/11 07:49
     * @return json
     */
    public function setUserCoupon()
    {
        global $_G,$_P,$_S,$_C;
        $themeid = isset($_P['themeid'])?$_P['themeid']:0;
        $uid = isset($_P['uid'])?$_P['uid']:0;
        $coupon_id = isset($_P['coupon_id'])?$_P['coupon_id']:0;
        if (!$themeid || !$uid || !$coupon_id){
            show_json(100,['msg'=>'参数缺失']);
        }
        //判断用户是否已经获取过
        $check_user_has_coupon = db_get(t_yx_coupon_user_flag,['themeid'=>$themeid,'coupon_id'=>$coupon_id,'uid'=>$uid]);
        if ($check_user_has_coupon){
            show_json(100,['msg'=>'补发优惠券失败，当前用户已经领取过次优惠券']);
        }
        //优惠券减库存 增加优惠券领取数
        CouponModel::couponSubQtyAndAddGetNum($themeid,$coupon_id);
        $data = ['themeid'=>$themeid,'uid'=>$uid,'workerid'=>0,'coupon_id'=>$coupon_id,'status'=>1];
        $res = CouponModel::userCouponEdit(0,[],$data);
        if ($res){
            return show_json(200,['msg'=>'补发优惠券成功']);
        }
        return show_json(100,['msg'=>'补发优惠券失败']);
    }

    public function getFloatLength($num)
    {
        $count = 0;
        $temp = explode ( '.', $num );
        if (sizeof ( $temp ) > 1) {
            $decimal = end ( $temp );
            $count = strlen ( $decimal );
        }
        return $count;
    }
}